Model binder maps HTML form elements to the model. It acts like a bridge between HTML UI and MVC model. Many times HTML UI names are different than the model property names.
So in the binder we can write the mapping logic between the UI and the model.
Now Bydefault, we call DefaultModelBinder class that are internally implement IModelBinder interface.
Create one class and implement IModelBinderinterface within it. In the below snippet, we have created “StudentModelBinder” custom binding class and implementedIModelBinderinterface. We have seen that IModelBindercontains only one method called BindModeland we have implemented the logic to map view property with the model property.
public class StudentModelBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var request = controllerContext.HttpContext.Request; string first_name = request.Form.Get("FirstName"); string last_name = request.Form.Get("LastName"); return new Person { full_name = first_name + last_name }; } }
Here, we are combining first_name and last_name to combine full name and returning Student object accordingly. Fine, now we will create the controller which will contain PostData() action and as parameter, it will take Student type object after binding in our custom StudentModelBinder class. Here is the simple implementation.
public class CustomodelbinderController : Controller { public ActionResult Index() { return View(); } public void PostData([ModelBinder(typeof(StudentModelBinder))] Student student) { } }
Now, we have to register the custom binder class in MVC pipeline. Now we Just add the below line in global.asax file.
ModelBinders.Binders.Add(typeof(Student), new StudentModelBinder());]
Finally, we have setup everything to bind model using our custom class.
Liked By
Write Answer
What is a MVC model binders?
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Join MindStick Community
You have need login or register for voting of answers or question.
Manoj Bhatt
18-Feb-2016Here is the view which will be mapped with the Student model.
Create one class and implement IModelBinder interface within it. In the below snippet, we have created “StudentModelBinder ” custom binding class and implemented IModelBinder interface. We have seen that IModelBinder contains only one method called BindModel and we have implemented the logic to map view property with the model property.
Now, we have to register the custom binder class in MVC pipeline. Now we Just add the below line in global.asax file.
ModelBinders.Binders.Add(typeof(Student), new StudentModelBinder());]